var fs=require('fs');
var path=require('path')
var Namen=require('./encryptionImg.js')
var userinfo = require('../../tools/NameList/index.js')

function saveImg(imgData,area,name){
	//过滤data:URL
	var _arr=imgData.split(',')
	var base64Data = _arr[1];
	var mime = _arr[0].match(/:(.*?);/)[1].split('/')[1];
	
	var src=path.join(__dirname,'../../public','images',area)
	deleteall(src)
	var url=path.join(src,Namen(name)+'.'+mime)
	var dataBuffer = new Buffer(base64Data, 'base64');
	return new Promise((resolve,reject)=>{
		fs.writeFile(url, dataBuffer, function(err) {
		    if(err){
		      reject('图片保存失败')
		    }else{
		     resolve({
					 state:200,
					 url:path.join('public','images',area,Namen(name)+'.'+mime)
				 })
		    }
		});
	})
	
}
function deleteall(path) {
	fs.mkdir(path,err=>{
	})
};

module.exports=function(req,images,title,genre){
	return new Promise((resolve,reject)=>{
		var info=userinfo(req)
		var len=0;
		var arr=[]
		images.forEach(async (item,index)=>{
			var name=info.name+info.Grade+info._id+title+genre+index;
			var result=await saveImg(item,info.name,name);
			len+=1;
			if(result.state==200){
				arr.push(result.url)
			}
			//保存完
			if(len>=images.length){
				resolve(arr)
			}
		})
	})
}
